﻿using StockWatcher.Facade;
using StockWatcher.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace StockWatcher
{
    public partial class StockWatcherForm : Form
    {
        #region 临时变量
        /// <summary>
        /// 当前选择股票代码
        /// </summary>
        string currentStockCode;
        /// <summary>
        /// 是否在运行
        /// </summary>
        bool isRunning;
        /// <summary>
        /// 最新接收的股票数据
        /// </summary>
        List<StockPriceInfo> receivedCurrentData;

        #endregion

        StockManager stockManager;
        AlertManager alertManager;

        public StockWatcherForm()
        {
            InitializeComponent();
            ConfigHelper.LoadStockConfig();
        }


        private void RefreshStockList()
        {
            listStocks.DataSource = SystemVar.StockConfigs.Values.ToList();
        }

        #region 股票管理
        private void button2_Click(object sender, EventArgs e)
        {
            EditStockForm form = new EditStockForm();
            if (form.ShowDialog() == DialogResult.OK)
            {
                SystemVar.StockConfigs.Add(form.StockInfo.RealCode, form.StockInfo);
                ConfigHelper.SaveStockConfig();
                RefreshStockList();

                stockManager.AddStock(form.StockInfo);
            }
        }
        private void btnStockEdit_Click(object sender, EventArgs e)
        {
            string code = listStocks.SelectedValue.ToString();
            if (String.IsNullOrEmpty(code))
                return;
            StockConfig stockInfo = SystemVar.StockConfigs[code];
            EditStockForm form = new EditStockForm();
            form.SetStockInfo(ref stockInfo);
            if (form.ShowDialog() == DialogResult.OK)
            {
                SystemVar.StockConfigs[code] = form.StockInfo;
                ConfigHelper.SaveStockConfig();
                RefreshStockList();

                stockManager.EditStock(form.StockInfo);
            }
        }

        private void btnStockDelete_Click(object sender, EventArgs e)
        {
            if (listStocks.SelectedItem == null)
                return;
            if (MessageBox.Show("确认删除["+ ((StockConfig)listStocks.SelectedItem).Name + "]?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                string code = listStocks.SelectedValue.ToString();
                SystemVar.StockConfigs.Remove(code);
                ConfigHelper.SaveStockConfig();
                RefreshStockList();

                stockManager.RemoveStock(code);
            }
        }
        #endregion

        private void StockWatcherForm_Load(object sender, EventArgs e)
        {
            RefreshStockList();
            stockManager = new StockManager(SystemVar.StockConfigs);
            alertManager = new AlertManager();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadStockData();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            switchToRunning();
            LoadStockData();
        }
        private void switchToRunning()
        {
            isRunning = true;
            groupStockAdmin.Enabled = false;

            nudTimeSpan.Enabled = false;
            btnStop.Enabled = true;
            btnStart.Enabled = false;

            tmrWorker.Interval = Convert.ToInt32(nudTimeSpan.Value) * 1000;
            tmrWorker.Start();
            pbSecCount.Maximum = Convert.ToInt32(nudTimeSpan.Value) - 1;
            pbSecCount.Value = 0;
            tmrProcessbar.Start();
        }

        private void switchToStop()
        {
            isRunning = false;
            nudTimeSpan.Enabled = true;
            btnStop.Enabled = false;
            btnStart.Enabled = true;
            groupStockAdmin.Enabled = true;
            tmrProcessbar.Stop();
            pbSecCount.Value = 0;
            tmrWorker.Stop();
        }
        private void btnStop_Click(object sender, EventArgs e)
        {
            switchToStop();
        }

        private void LoadStockData()
        {
            receivedCurrentData = new List<StockPriceInfo>();
            try
            {
                var stocks = stockManager.StockConfigs;
                if (stocks.Count < 1)
                {
                    lbMessage.Text = "没有设定要查看哪只股票";
                    return;
                }
                receivedCurrentData = SinaDataSource.ReadData(stocks.Keys.ToList());
                alertManager.SetAlert(stockManager.CheckData(receivedCurrentData));
                RenderData(new Tuple<List<StockPriceInfo>, Dictionary<string, AlertResultForList>>(receivedCurrentData, alertManager.CurrentAlertForList));
                SendAlert();
                if (!string.IsNullOrEmpty(currentStockCode) &&
                    (new FormWindowState[] { FormWindowState.Maximized, FormWindowState.Normal }).Contains(this.WindowState))//最小化的时候不自动刷新
                    ShowDetail(currentStockCode);
            }
            catch (Exception ex)
            {
                lbMessage.Text = ex.Message;
            }
        }


        private void SendAlert()
        {
            foreach (var alert in alertManager.CurrentAlertShouldSend)
            {
                string message = String.Format("[{0}]:{1}", alert.Name, alert.AlertMessage);
                if (SystemVar.noteForm == null || SystemVar.noteForm.IsDisposed)
                {
                    SystemVar.noteForm = new FrmNote(
                      "股价提示", message
                     );
                    SystemVar.noteForm.Show();
                }
                else
                {
                    SystemVar.noteForm.AppendMessage(message);
                }
            }
        }


        private void RenderData(object dataObj)
        {
            if (lvStockList.InvokeRequired)
            {
                this.Invoke(new Action<object>(RenderData), dataObj);
            }
            else
            {
                List<StockPriceInfo> data = ((Tuple<List<StockPriceInfo>, Dictionary<string, AlertResultForList>>)dataObj).Item1;
                Dictionary<string, AlertResultForList> alert = ((Tuple<List<StockPriceInfo>, Dictionary<string, AlertResultForList>>)dataObj).Item2;

                this.lvStockList.Items.Clear();
                lvStockList.BeginUpdate();
                for (int i = 0; i < data.Count; i++)
                {
                    ListViewItem lvi = new ListViewItem();
                    lvi.Text = data[i].股票代码;
                    lvi.BackColor = Color.White;
                    if (data[i].涨幅 > 0)
                        lvi.ForeColor = Color.Red;
                    else if (data[i].涨幅 == 0)
                        lvi.ForeColor = Color.Black;
                    else
                        lvi.ForeColor = Color.Green;

                    if (!string.IsNullOrEmpty(data[i].股票名字))
                    {
                        double earnRate = 100 * (data[i].当前价格 - data[i].成本价格) / data[i].成本价格;
                        lvi.SubItems.Add(data[i].股票名字);
                        lvi.SubItems.Add(alert[data[i].股票代码].AlertLogos);
                        lvi.SubItems.Add(data[i].当前价格.ToString("F2"));
                        lvi.SubItems.Add(string.Format("{0}/{1}%", data[i].成本价格.ToString("F2"), earnRate.ToString("F2")));
                        lvi.SubItems.Add(data[i].涨幅.ToString("F2") + "%");
                        lvi.SubItems.Add(data[i].成交的股票数.ToString("0,00"));
                        lvi.SubItems.Add(data[i].今日最高价.ToString("F2"));
                        lvi.SubItems.Add(data[i].今日最低价.ToString("F2"));
                    }
                    this.lvStockList.Items.Add(lvi);
                }
                lvStockList.EndUpdate();
            }
        }

        private void lvStockList_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListView lvStocks = (ListView)sender;
            if (lvStocks.SelectedItems.Count < 1)
                return;
            currentStockCode = lvStocks.SelectedItems[0].Text;
            ShowDetail(currentStockCode);
        }
        private void ShowDetail(string code)
        {
            var stock = receivedCurrentData.Find(a => a.股票代码 == code);
            if (stock == null)
                return;
            picStockPrice.Image = SinaDataSource.GetStockImage(code);

            txtStockDetail.Text = StockHelper.GetStockDetailString(stock);
            txtAlert.Text = String.Join("\r\n", alertManager.CurrentAlertForList[stock.股票代码].AlertMessages);
        }
        /// <summary>
        /// 重置提醒信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbMessage_Click(object sender, EventArgs e)
        {
            lbMessage.Text = "祝君发大财.";
        }

        private void tmrProcessbar_Tick(object sender, EventArgs e)
        {
            changeProcessbarValue();
        }

        private void changeProcessbarValue()
        {
            if (pbSecCount.InvokeRequired)
                this.Invoke(new Action(changeProcessbarValue));
            else
            {
                if (pbSecCount.Value < pbSecCount.Maximum)
                    pbSecCount.Value += 1;
                else
                    pbSecCount.Value = 0;
            }
        }
        private void tmrWorker_Tick(object sender, EventArgs e)
        {
            LoadStockData();
        }
        /// <summary>
        /// 窗口还原或者最大化的时候自动刷新一下详情.免得最小化期间没有刷新,打开之后看到的是旧的图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StockWatcherForm_SizeChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(currentStockCode) &&
                     (new FormWindowState[] { FormWindowState.Maximized, FormWindowState.Normal }).Contains(this.WindowState))
                ShowDetail(currentStockCode);
        }
    }
}
